﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace TreeTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            GetTreeFromFile(Application.StartupPath +"\\temp.txt", treeView1);
        }


        private void TreeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (treeView1.SelectedNode != null)
            {
                textBox3.Text = treeView1.SelectedNode.Text;
                textBox4.Text = treeView1.SelectedNode.Name;
                textBox5.Text = treeView1.SelectedNode.Level.ToString();
                textBox6.Text = treeView1.SelectedNode.FullPath;
            }


        }

        
        #region 通用功能

        /// <summary>
        ///  将文本文件内容读取到 TreeView 中，删除空白行，并以整理后的第2行的行首空格为缩进标准进行导入
        /// </summary>
        /// <param name="filename">要导入的文本文件</param>
        /// <param name="treeView">要操作的 TreeView</param>
        public void GetTreeFromFile(string filename, TreeView treeView)
        {
            List<string> list = GetFile(filename);          // 读取文本文件到字符串列表
            treeView.Nodes.Clear();                         // 清除 TreeView 的所有节点
            int blanks = HeaderBlanks(list[1].ToString());  // 按字符串列表的第2个值计算行首空白字符数
            if (blanks == 0) { blanks = 1; }                // 

            Dictionary<int, TreeNode> nodeDict = new Dictionary<int, TreeNode>();

            foreach (string st in list)
            {
                int level = HeaderBlanks(st) / blanks;
                if (level == 0) { nodeDict[level] = treeView.Nodes.Add(st.Trim()); }
                else { nodeDict[level] = nodeDict[level - 1].Nodes.Add(st.Trim()); }
                nodeDict[level].EnsureVisible();

            }

            if (treeView.Nodes.Count > 0) { treeView.Nodes[0].EnsureVisible(); }

        }

        /// <summary>
        ///  读取文本文件，删除空行（包括只含空格及制表符的行），返回字符串列表
        /// </summary>
        /// <param name="add">文本文件的路径</param>
        /// <returns>文本文件的字符串列表</returns>
        public List<string> GetFile(string add)
        {
            List<string> ls = new List<string>();
            string[] lines = System.IO.File.ReadAllLines(add);

            foreach (string st in lines)
            {
                if (!String.IsNullOrWhiteSpace(st)) { ls.Add(st); }
            }

            return ls;
        }

        /// <summary>
        ///  计算行首的空格或制表符的个数
        /// </summary>
        /// <param name="st">要计算行首空白数的字符串</param>
        /// <returns>字符串的空白数量</returns>
        public static int HeaderBlanks(string st)
        {
            return st.Length - st.TrimStart().Length;
        }


        #endregion

    }
}
